package com.tevintao.marketingsystem.task;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tevintao.marketingsystem.commen.UrlConfig;
import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.provider.ChatNewChatDB;
import com.tevintao.marketingsystem.services.AccountManager;
import com.tevintao.marketingsystem.tool.UploadFileTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class ReportMessage {

    @SuppressLint("SdCardPath")
    private static final String MM_SD_PATH = "/mnt/sdcard/tencent/micromsg/";
    private static final int MESSAGE_TYPE_WORLD = 1;//文字
    public static final int MESSAGE_TYPE_PICTURE = 3;//图片
    public static final int MESSAGE_TYPE_VOICE = 34;//语音
    public static final int MESSAGE_TYPE_VIDEO = 43; //小视屏
    public static final int MESSAGE_TYPE_WARING = 10000;//系统消息
    private static final int MESSAGE_TYPE_COLLECTION = 49;//收藏
    //    public static final int MESSAGE_TYPE_LOCATION = 48;//发送的位置信息
//    public static final int MESSAGE_TYPE_SHARE_LOCATION = -1879048186;//共享实时位置
    public static final int MESSAGE_TYPE_HONG_BAO = 436207665;//红包
    public static final int MESSAGE_TYPE_ZHUAN_ZHANG = 419430449;//转账

    private static final int MAX_RETRY_TIMES = 3;

    public static final String KEY_PARAMS_ACCOUNT = "account";
    public static final String KEY_PARAMS_TALKER = "talker";
    public static final String KEY_PARAMS_NIKE_NAME = "nickName";
    public static final String KEY_PARAMS_CONTENT = "content";
    public static final String KEY_PARAMS_CREATE_TIME = "createTime";
    public static final String KEY_PARAMS_TYPE = "type";
    public static final String KEY_FROM_ANDROID = "fromAndroid";
    public static final String KEY_FROM_FILE_PATH = "filePath";


    public static final String SEX_TYPE_NONE = "未知";
    private RequestQueue requestQueue;

    private static Context mContext;
    private static ReportMessage ourInstance = new ReportMessage();

    public static ReportMessage getInstance(Context context) {
        if (null == mContext) {
            mContext = context;
        }

        return ourInstance;
    }

    private ReportMessage() {
    }

    public boolean report(String account, String talker, String nikeName, String imgPath, String content, long createTime, int type, boolean reportNow) {

        if (MESSAGE_TYPE_PICTURE == type) {
            content = "图片";
        } else if (MESSAGE_TYPE_COLLECTION == type) {
            content = "收藏";
        }

        if (type == MESSAGE_TYPE_WORLD || type == MESSAGE_TYPE_WARING || type == MESSAGE_TYPE_HONG_BAO || type == MESSAGE_TYPE_ZHUAN_ZHANG) {
            imgPath = "";
        }
        long insertMessage = ChatNewChatDB.getInstance().insertSendMessage(account, talker, nikeName, imgPath, content, createTime, type);
        LogManager.getInstance().logError("insertSendMessage = " + insertMessage);
        if (reportNow) { //立即上报
            LogManager.getInstance().logInfo("立即上报消息");
            startReportLocalMessage();
        }
        /*if (type == MESSAGE_TYPE_WORLD || type == MESSAGE_TYPE_WARING || type == MESSAGE_TYPE_HONG_BAO || type == MESSAGE_TYPE_ZHUAN_ZHANG) {
            HashMap<String, String> params = new HashMap<>();
            params.put(KEY_PARAMS_ACCOUNT, account);
            params.put(KEY_PARAMS_TALKER, talker);
            params.put(KEY_PARAMS_NIKE_NAME, nikeName);
            params.put(KEY_PARAMS_CONTENT, content);
            params.put(KEY_PARAMS_CREATE_TIME, "" + createTime);
            params.put(KEY_PARAMS_TYPE, "" + type);
            params.put(KEY_FROM_ANDROID, "" + 1);
            postChatMessage(UrlConfig.URL_UPDATE_MESSAGE, params, 0);
        } else if (type == MESSAGE_TYPE_PICTURE || type == MESSAGE_TYPE_VOICE || type == MESSAGE_TYPE_VIDEO) {
            //"/chat/updateFile?account=%s&talker=%s&nikeName=%s&type=%s&content=%s&createTime=%s";
            try {
                account = URLEncoder.encode(account, "UTF-8");
                talker = URLEncoder.encode(talker, "UTF-8");
                nikeName = URLEncoder.encode(nikeName, "UTF-8");
                content = URLEncoder.encode(content, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            final String url = String.format(UrlConfig.URL_UPDATE_FILE_MESSAGE, account, talker, nikeName, type, content, createTime);


            String realPath;
            LogManager.getInstance().logInfo("url = " + url);
//            "/chat/updateFile?account=%s&talker=%s&nikeName=%s&type=%s&content=%s&createTime=%s"
            if (type == MESSAGE_TYPE_PICTURE) {
                realPath = getImagePath(imgPath);
                LogManager.getInstance().logInfo("realPath = " + realPath);
                if (TextUtils.isEmpty(realPath)) {
                    LogManager.getInstance().logError("没找到图片到路劲");
                    return false;
                }
            } else if (type == MESSAGE_TYPE_VOICE) {
                realPath = getVoicePath(imgPath);
                LogManager.getInstance().logInfo("realPath = " + realPath);
                if (TextUtils.isEmpty(realPath)) {
                    LogManager.getInstance().logError("没找到音频到路劲");
                    return false;
                }
            } else {
                realPath = getVideoPath(imgPath);
                LogManager.getInstance().logInfo("realPath = " + realPath);
                if (TextUtils.isEmpty(realPath)) {
                    LogManager.getInstance().logError("没找到音频到路劲");
                    return false;
                }
            }
            if (TextUtils.isEmpty(realPath)) {
                LogManager.getInstance().logInfo("真实路劲错误");
                return false;
            }

            final String finalRealPath = realPath;
            for (int i = 0; i < MAX_RETRY_TIMES; i++) {
                String result = UploadFileTool.uploadFile(url, finalRealPath);
                if (!TextUtils.isEmpty(result)) {
                    LogManager.getInstance().logInfo("上传文件成功" + result);
                    break;
                }
                if (i >= MAX_RETRY_TIMES - 1) {
                    LogManager.getInstance().logInfo("上传文件多次失败");
                }
            }

        }*/

        return false;
    }

    private HashSet<String> mReportingIds = new HashSet<>();

    public void startReportLocalMessage() {
        Cursor cursor = ChatNewChatDB.getInstance().getNeedReportMessage();
        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex("id"));
            if (mReportingIds.contains(id)) {
                continue;
            } else {
                mReportingIds.add(id);
            }
            String account = cursor.getString(cursor.getColumnIndex("account"));
            String talker = cursor.getString(cursor.getColumnIndex("talker"));
            String nikeName = cursor.getString(cursor.getColumnIndex("nikeName"));
            String imgPath = cursor.getString(cursor.getColumnIndex("imgPath"));
            String content = cursor.getString(cursor.getColumnIndex("content"));
            String createTime = cursor.getString(cursor.getColumnIndex("createTime"));
            int type = cursor.getInt(cursor.getColumnIndex("type"));
            LogManager.getInstance().logInfo("startReportLocalMessage id = " + id + " account " + account + " talker = " + talker + " nikeName = " + nikeName + " imgPath = " + imgPath + " content = " + content + " createTime " + createTime);
            if (type == MESSAGE_TYPE_WORLD || type == MESSAGE_TYPE_WARING || type == MESSAGE_TYPE_HONG_BAO || type == MESSAGE_TYPE_ZHUAN_ZHANG) {
                HashMap<String, String> params = new HashMap<>();
                params.put("localId", "-" + id);
                params.put("saveUseId", id);

//
//                params.put(KEY_PARAMS_ACCOUNT, account);
//                params.put(KEY_PARAMS_TALKER, talker);
//                params.put(KEY_PARAMS_NIKE_NAME, nikeName);
//                params.put(KEY_PARAMS_CONTENT, content);
//                params.put(KEY_PARAMS_CREATE_TIME, "" + createTime);
//                params.put(KEY_PARAMS_TYPE, "" + type);
//                params.put(KEY_FROM_ANDROID, "" + 1);

                params.put(KEY_PARAMS_ACCOUNT, account);
                params.put(KEY_PARAMS_TALKER, talker);
                params.put(KEY_PARAMS_NIKE_NAME, nikeName);
                params.put("imgPath", imgPath);
                params.put(KEY_PARAMS_CONTENT, content);
                params.put(KEY_PARAMS_CREATE_TIME, createTime);
                params.put(KEY_PARAMS_TYPE, "" + type);
                params.put(KEY_FROM_ANDROID, "" + 1);
                postChatMessage(UrlConfig.URL_UPDATE_MESSAGE, params, 0);
            } else if (type == MESSAGE_TYPE_PICTURE || type == MESSAGE_TYPE_VOICE || type == MESSAGE_TYPE_VIDEO) {
                //"/chat/updateFile?account=%s&talker=%s&nikeName=%s&type=%s&content=%s&createTime=%s";
                try {
                    account = URLEncoder.encode(account, "UTF-8");
                    talker = URLEncoder.encode(talker, "UTF-8");
                    nikeName = URLEncoder.encode(nikeName, "UTF-8");
                    content = URLEncoder.encode(content, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                final String url = String.format(UrlConfig.URL_UPDATE_FILE_MESSAGE, account, talker, nikeName, type, content, createTime, "-" + id);


                String realPath;
                LogManager.getInstance().logInfo("url = " + url);
//            "/chat/updateFile?account=%s&talker=%s&nikeName=%s&type=%s&content=%s&createTime=%s"
                if (type == MESSAGE_TYPE_PICTURE) {
                    realPath = getImagePath(imgPath);
                    LogManager.getInstance().logInfo("realPath = " + realPath);
                    if (TextUtils.isEmpty(realPath)) {
                        LogManager.getInstance().logError("没找到图片到路劲");
                        continue;
                    }
                } else if (type == MESSAGE_TYPE_VOICE) {
                    realPath = getVoicePath(imgPath);
                    LogManager.getInstance().logInfo("realPath = " + realPath);
                    if (TextUtils.isEmpty(realPath)) {
                        LogManager.getInstance().logError("没找到音频到路劲");
                        continue;
                    }
                } else {
                    realPath = getVideoPath(imgPath);
                    LogManager.getInstance().logInfo("realPath = " + realPath);
                    if (TextUtils.isEmpty(realPath)) {
                        LogManager.getInstance().logError("没找到音频到路劲");
                        continue;
                    }
                }
                if (TextUtils.isEmpty(realPath)) {
                    LogManager.getInstance().logInfo("真实路劲错误");
                    continue;
                }

                final String finalRealPath = realPath;
                for (int i = 0; i < MAX_RETRY_TIMES; i++) {
                    String result = UploadFileTool.uploadFile(url, finalRealPath);
                    mReportingIds.remove(id);
                    if (!TextUtils.isEmpty(result)) {
                        LogManager.getInstance().logInfo("上传文件成功" + result);
                        long updateSuccess = ChatNewChatDB.getInstance().updateSuccess(id);
                        LogManager.getInstance().logInfo("上报消息成功 保存到数据库  = " + updateSuccess);
                        saveSendMsg("YES " + url);
                        break;
                    }
                    if (i >= MAX_RETRY_TIMES - 1) {
                        LogManager.getInstance().logInfo("上传文件多次失败");
                        long updateFailed = ChatNewChatDB.getInstance().uploadFailed(id);
                        LogManager.getInstance().logInfo("上报消息失败 保存到数据库  = " + updateFailed);
                        saveSendMsg("FAILED " + url);
                    }
                }

            }
        }
        cursor.close();

    }

    private void postChatMessage(final String url, final Map<String, String> params, final int retryTimes) {
        if (null == requestQueue) {
            requestQueue = Volley.newRequestQueue(mContext);
        }
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String reportId = params.get("saveUseId");

                        long updateSuccess = ChatNewChatDB.getInstance().updateSuccess(reportId);
                        LogManager.getInstance().logInfo("上报消息成功 保存到数据库  = " + updateSuccess + " reportId = " + reportId);
                        saveSendMsg("YES " + params.toString());
                        mReportingIds.remove(reportId);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                LogManager.getInstance().logInfo("上报消息失败 " + error.toString());
                String reportId = params.get("saveUseId");

                long updateFailed = ChatNewChatDB.getInstance().uploadFailed(reportId);
                LogManager.getInstance().logInfo("上报消息失败 保存到数据库  = " + updateFailed);
                saveSendMsg("FAILED " + params.toString());
                mReportingIds.remove(reportId);
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                return params;
            }
        };
        requestQueue.add(stringRequest);
    }

    private String getVideoPath(String fileName) {
        File rootFile = new File(MM_SD_PATH);
        File[] accountFiles = rootFile.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().length() == "4bd870110c1017a763c0f412b9dd3e2d".length();
            }
        });
        String realName = fileName + ".jpg";

        for (File checkFile : accountFiles) {
            String checkPath = MM_SD_PATH + checkFile.getName() + "/video/" + realName;
            if (new File(checkPath).exists()) {
                LogManager.getInstance().logInfo("找到文件 " + checkPath);
                return checkPath;
            }
        }
        return null;
    }

    private String getVoicePath(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return null;
        }
        File rootFile = new File(MM_SD_PATH);
        File[] accountFiles = rootFile.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().length() == "4bd870110c1017a763c0f412b9dd3e2d".length();
            }
        });

        String realFileName = "msg_" + fileName + ".amr";
        for (File checkFile : accountFiles) {
            String checkPath = MM_SD_PATH + checkFile.getName() + "/voice2";
            String findPath = searchFileFromPath(new File(checkPath), realFileName);
//            LogManager.getInstance().logInfo("findPath = " + findPath);
            if (null != findPath && new File(findPath).exists()) {
                LogManager.getInstance().logInfo("找到文件 " + findPath);
                return findPath;
            }
        }
        return null;
    }

    private String searchFileFromPath(File rootFile, String searchFileName) {
        if (null == rootFile || !rootFile.exists()) {
            return null;
        }
        if (rootFile.isDirectory()) {
            File[] files = rootFile.listFiles();
            for (File childFile : files) {
                if (childFile.isDirectory()) {
                    String findFilePath = searchFileFromPath(childFile, searchFileName);
                    if (!TextUtils.isEmpty(findFilePath)) {
                        return findFilePath;
                    }
                } else if (childFile.isFile() && childFile.getName().equals(searchFileName)) {
                    return childFile.getAbsolutePath();
                }
            }
        }
        return null;
    }


    private String getImagePath(String path) {
//        String path = "THUMBNAIL_DIRPATH://th_fba359af70fb7927e525b5df4a27b5de";
        File rootFile = new File(MM_SD_PATH);
        File[] accountFiles = rootFile.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().length() == "4bd870110c1017a763c0f412b9dd3e2d".length();
            }
        });

        String dir = path.substring(23, 25);
        String dir2 = path.substring(25, 27);
        LogManager.getInstance().logInfo("dir1 = " + dir + " dir2 = " + dir2);

        for (File checkFile : accountFiles) {
            String checkPath = MM_SD_PATH + checkFile.getName() + "/image2/" + dir + "/" + dir2 + "/" + path.substring(20);
            LogManager.getInstance().logInfo("checkFile.getName() = " + checkFile.getName() + " checkPath = " + checkPath);
            if (new File(checkPath).exists()) {
                LogManager.getInstance().logInfo("文件位置 " + checkPath);
                return checkPath;
            }
        }
        return null;
    }

    private void saveSendMsg(String content) {
        try {
            //打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(AccountManager.SEND_MESSAGE_FILE, true);
            writer.write(content + "\r\n");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
